package com.guoheng.hazard.sys.service.impl.entpr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guoheng.hazard.common.base.Result;
import com.guoheng.hazard.common.constant.CommonConstants;
import com.guoheng.hazard.common.enums.ErrorCodeEnum;
import com.guoheng.hazard.common.enums.PartTypeEnum;
import com.guoheng.hazard.common.util.StringUtils;
import com.guoheng.hazard.sys.mapper.entpr.EntprBasicInfoMapper;
import com.guoheng.hazard.sys.mapper.entpr.MajorHazardMaterialMapper;
import com.guoheng.hazard.sys.mapper.entpr.ProductionPlaceMapper;
import com.guoheng.hazard.sys.model.dto.entpr.EntprScopeDTO;
import com.guoheng.hazard.sys.model.dto.entpr.ProductionPlaceInsertDTO;
import com.guoheng.hazard.sys.model.dto.entpr.ProductionPlaceSelectDTO;
import com.guoheng.hazard.sys.model.dto.entpr.ProductionPlaceUpdateDTO;
import com.guoheng.hazard.sys.model.dto.hazard.MajorHazardMaterialInsertDTO;
import com.guoheng.hazard.sys.model.dto.hazard.MajorHazardMaterialSelectDTO;
import com.guoheng.hazard.sys.model.entity.entpr.EntprBasicInfo;
import com.guoheng.hazard.sys.model.entity.entpr.MajorHazardMaterial;
import com.guoheng.hazard.sys.model.entity.entpr.ProductionPlace;
import com.guoheng.hazard.sys.service.entpr.ProductionPlaceService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 类功能描述:　ProductionPlaceService
 *
 * @author fbl
 * @date 2019-44-13 17:44
 */
@Service
public class ProductionPlaceServiceImpl implements ProductionPlaceService {


    @Resource
    private ProductionPlaceMapper productionPlaceMapper;

    @Resource
    EntprBasicInfoMapper entprBasicInfoMapper;

    @Resource
    MajorHazardMaterialMapper majorHazardMaterialMapper;


    @Override
    public Result getPlace(String entprName, String placeNo, Long entprId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProductionPlaceSelectDTO> place = productionPlaceMapper.getPlace(entprName, placeNo, entprId);
        for (ProductionPlaceSelectDTO productionPlace : place) {
            // 查询企业姓名
            Long eId = productionPlace.getEntprId();
            EntprBasicInfo entprBasicInfoById = entprBasicInfoMapper.getEntprBasicInfoById(eId);
            productionPlace.setEntprName(entprBasicInfoById.getEntprName());
            // 查询生产场所介质
            List<MajorHazardMaterial> materials = majorHazardMaterialMapper.getMajorMaterial(3, productionPlace.getId());
            productionPlace.setMajorHazardMaterials(materials);
        }

        PageInfo<ProductionPlaceSelectDTO> productionPlacePageInfo = new PageInfo<>(place);

        return Result.success(productionPlacePageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updatePlace(ProductionPlaceUpdateDTO productionPlaceUpdateDTO) {
        // 修改生产场所基本信息
        ProductionPlace productionPlace = new ProductionPlace();
        BeanUtils.copyProperties(productionPlaceUpdateDTO, productionPlace);

        // 生产场所编号不能重复
        ProductionPlace placeById = productionPlaceMapper.getPlaceById(productionPlace.getId());
        if (!placeById.getPlaceNo().equals(productionPlace.getPlaceNo())) {
            List<ProductionPlace> allPlaces = productionPlaceMapper.getAllPlaces(productionPlace.getEntprId());
            for (ProductionPlace allPlace : allPlaces) {
                // 生产场所编号重复
                if (allPlace.getPlaceNo().equals(productionPlace.getPlaceNo())) {
                    return Result.failure(ErrorCodeEnum.SYS_ERR_PLACE_NO_REPEAT);
                }
            }
        }
        int updatePlace = productionPlaceMapper.updatePlace(productionPlace);
        if (productionPlaceUpdateDTO.getMajorHazardMaterialInsertDTOS() != null) {
            // 清空场所中的介质信息
            majorHazardMaterialMapper.clearMaterial(PartTypeEnum.PART_TYPE_THREE.getCode(),productionPlaceUpdateDTO.getId());
            List<MajorHazardMaterialSelectDTO> majorHazardMaterialSelectDTOS = productionPlaceUpdateDTO.getMajorHazardMaterialInsertDTOS();
            for (MajorHazardMaterialSelectDTO majorHazardMaterialSelectDTO : majorHazardMaterialSelectDTOS) {
                MajorHazardMaterial majorHazardMaterial = new MajorHazardMaterial();
                BeanUtils.copyProperties(majorHazardMaterialSelectDTO, majorHazardMaterial);
                majorHazardMaterial.setPartId(productionPlaceUpdateDTO.getId());
                majorHazardMaterial.setPartType(PartTypeEnum.PART_TYPE_THREE.getCode());
                majorHazardMaterialMapper.insertSelective(majorHazardMaterial);
            }
        }
        if (updatePlace == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("修改数据失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insertPlace(ProductionPlaceInsertDTO productionPlaceInsertDTO) {
        // 新增场所
        ProductionPlace productionPlace = new ProductionPlace();
        BeanUtils.copyProperties(productionPlaceInsertDTO, productionPlace);
        // 生产场所编号不能重复
        List<ProductionPlace> allPlaces = productionPlaceMapper.getAllPlaces(productionPlace.getEntprId());
        for (ProductionPlace allPlace : allPlaces) {
            // 生产场所编号重复
            if (allPlace.getPlaceNo().equals(productionPlace.getPlaceNo())) {
                return Result.failure(ErrorCodeEnum.SYS_ERR_PLACE_NO_REPEAT);
            }
        }
        int insertPlace = productionPlaceMapper.insertPlace(productionPlace);
        // 查询刚刚新增的场所id
        Long lastPlaceId = productionPlaceMapper.getLastPlace();

        // 新增场所中的介质
        if (productionPlaceInsertDTO.getMajorHazardMaterialInsertDTOS() != null) {
            List<MajorHazardMaterialInsertDTO> majorHazardMaterialInsertDTOS = productionPlaceInsertDTO.getMajorHazardMaterialInsertDTOS();
            for (MajorHazardMaterialInsertDTO majorHazardMaterialInsertDTO : majorHazardMaterialInsertDTOS) {
                MajorHazardMaterial majorHazardMaterial = new MajorHazardMaterial();
                BeanUtils.copyProperties(majorHazardMaterialInsertDTO, majorHazardMaterial);
                majorHazardMaterial.setPartId(lastPlaceId);
                majorHazardMaterial.setPartType(PartTypeEnum.PART_TYPE_THREE.getCode());
                majorHazardMaterialMapper.insertSelective(majorHazardMaterial);
            }

        }
        if (insertPlace == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("新增失败");
        }
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deletePlace(Long id) {
        // 删除生产场所
        ProductionPlace productionPlace = new ProductionPlace();
        productionPlace.setId(id);
        productionPlace.setDelFlag(true);
        int deletePlace = productionPlaceMapper.updatePlace(productionPlace);
        // 删除生产场所下的介质
        majorHazardMaterialMapper.deleteMaterial(PartTypeEnum.PART_TYPE_THREE.getCode(), id);
        if (deletePlace == CommonConstants.DataBaseOperationStatus.IS_FAILURE) {
            throw new RuntimeException("删除失败");
        }
        return Result.success();
    }

    @Override
    public Result getPlaceById(Long id) {
        ProductionPlaceSelectDTO productionPlaceSelectDTO = new ProductionPlaceSelectDTO();
        // 查询场所的详细信息
        ProductionPlace placeById = productionPlaceMapper.getPlaceById(id);
        BeanUtils.copyProperties(placeById, productionPlaceSelectDTO);
        // 查询介质的详细信息
        List<MajorHazardMaterial> majorMaterial = majorHazardMaterialMapper.getMajorMaterial(PartTypeEnum.PART_TYPE_THREE.getCode(), id);
        productionPlaceSelectDTO.setMajorHazardMaterials(majorMaterial);
        // 所属企业
        Long entprId = placeById.getEntprId();
        EntprBasicInfo entprBasicInfo = entprBasicInfoMapper.getEntprBasicInfoById(entprId);
        String entprScope = entprBasicInfo.getEntprScope();
        if (StringUtils.isNotEmpty(entprScope)) {
            entprScope = "{\"data\":" + entprScope + "}";
            JSONObject jsonObject = JSON.parseObject(entprScope);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            List<EntprScopeDTO> entprScopeDTOS = jsonArray.toJavaList(EntprScopeDTO.class);
            productionPlaceSelectDTO.setEntprScope(entprScopeDTOS);
        }else{
            productionPlaceSelectDTO.setEntprScope(new ArrayList<>());
        }
        return Result.success(productionPlaceSelectDTO);
    }
}
